
//
//  StatusViewModel.swift
//  Practice
//
//  Created by miaozhihui on 2017/1/17.
//  Copyright © 2017年 DeKuTree. All rights reserved.
//

import Foundation
import SDWebImage

// 上拉刷新最大尝试次数
private let maxPullUpTryTimes = 3

/// 微博列表视图模型
class StatusListViewModel {
    
    /// 微博视图模型数组
    lazy var statusViewModelList = [StatusViewModel]()
    
    /// 上拉刷新错误次数
    private var pullUpErrorTimes = 0
    
    /// 加载微博列表
    ///
    /// - Parameters:
    ///   - isPullUp: 是否上拉刷新
    ///   - completion: 完成回调[网络请求是否成功,是否刷新表格]
    func loadStatus(isPullUp:Bool, completion:@escaping (_ isSuccess:Bool,_ shouldRefresh:Bool)->()) {
        
        // 如果是上拉刷新，并且错误次数大于最大尝试次数
        if isPullUp && pullUpErrorTimes > maxPullUpTryTimes {
            completion(true, false)
            return
        }
        // 取出数组中第一条微博的id
        let since_id = isPullUp ? 0 : (statusViewModelList.first?.status.id ?? 0)
        
        // 取出数组中最后一条微博的id
        let max_id = !isPullUp ? 0 : (statusViewModelList.last?.status.id ?? 0)
        
        
        NetworkTools.sharedTools.statusList(since_id: since_id,max_id: max_id) { (list, isSuccess) in
            
            // 判断是否成功
            if !isSuccess {
                completion(false, false)
                return
            }
            // 字典转模型
            var array = [StatusViewModel]()
            for dict in list ?? [] {
//                print(dict["pic_urls"])
                guard let model = Status.yy_model(with: dict) else {
                    continue
                }
                array.append(StatusViewModel(model: model))
            }
            
            print("刷新到\(array.count)条数据 \(array)")
            
            // 拼接数组
            if isPullUp {
                self.statusViewModelList += array
            } else {
                self.statusViewModelList = array + self.statusViewModelList
            }
            
            if isPullUp && array.count == 0 {
                self.pullUpErrorTimes += 1
                completion(isSuccess, false)
            } else {
                self.cacheSingleImage(list: array,completion: completion)
            }
        }
    }
    
    /// 缓存本次下载的微博数据数组中的单张图像
    ///
    /// - Parameter list: 本次下载的视图模型数组
    private func cacheSingleImage(list:[StatusViewModel], completion:@escaping (_ isSuccess:Bool,_ shouldRefresh:Bool)->()) {
        
        // 调度组
        let group = DispatchGroup()
    
        var length = 0
        // 遍历数组，查找微博数据中有单张图像的，进行缓存
        for vm in list {
            
            // 如果数量不为1 ，不缓存
            if vm.picURLs?.count != 1 {
                continue
            }
            
            guard let pic_url = vm.picURLs?[0].thumbnail_pic,
                let url = URL(string: pic_url) else {
                    continue
            }
            
            // 入组
            group.enter()
            
            print("要缓存的 URL 是:\(url)")
            SDWebImageManager.shared().downloadImage(with: url, options: [], progress: nil, completed: { (image, _, _, _, url) in
                if let image = image {
                    
                    let data = UIImagePNGRepresentation(image)
                    
                    length += data?.count ?? 0
                    
                    // 图像缓存成功，更新配图视图的大小
                    vm.updateSingleImageSize(image: image)
                }
                print("缓存的图像是:\(image)\(length)")
                // 出组
                group.leave()
            })
            
        }
        
        // 监听调度组情况
        group.notify(queue: DispatchQueue.main) { 
            print("图像缓存完成\(length/1024)K")
            
            completion(true,true)
        }
        
    }
}
